﻿using System;
using System.Data.Linq;
using System.Linq;
using Safal.IncidentTracker.Domain.Abstract;
using Safal.IncidentTracker.Domain.Entities;

namespace Safal.IncidentTracker.Domain.Concrete
{
    public class SqlIncidentsRepository : IIncidentsRepository
    {
        private Table<Incident> _incidents;

        public SqlIncidentsRepository(string connectionString)
        {
            _incidents = (new DataContext(connectionString)).GetTable<Incident>();
        }

        public IQueryable<Incident> Incidents
        {
            get { return _incidents; }
        }

        public void SaveIncident(Incident incident)
        {
            if (incident.Id == 0)
            {
                incident.DateOfIncident = DateTime.Now;
                _incidents.InsertOnSubmit(incident);
            }
            else if (_incidents.GetOriginalEntityState(incident) == null)
            {
                _incidents.Attach(incident);
                _incidents.Context.Refresh(RefreshMode.KeepCurrentValues, incident);
            }
            _incidents.Context.SubmitChanges();
        }

        public void DeleteIncident(Incident incident) {
            _incidents.DeleteOnSubmit(incident);
            _incidents.Context.SubmitChanges();
        }
    }
}
